﻿/*
 *  ChgDoc CMS - GNU General Public License, version 3 (GPL-3.0)
 *  Copyright (C)  2012. Ian Quigley
 *  
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *  
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 */

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ChgDoc.Entity;
using System.Web;
using System.Reflection;

namespace ChgDoc.Render
{
    public class CustomResponseRenderAttribute : System.Attribute
    {
        public int Id { get; private set; }

        public CustomResponseRenderAttribute(int id)
        {
            Id = id;
        }
    }

    public abstract class ResponseRender 
    {
        private static List<KeyValuePair<int, Type>> _responseRender;

        private static List<KeyValuePair<int, Type>> Defaults()
        {
            return new List<KeyValuePair<int, Type>>()
            {
                new KeyValuePair<int, Type>((int)PageRender.Template, typeof(TemplateRender)),
                new KeyValuePair<int, Type>((int)PageRender.TemplateData, typeof(TemplateDataRender)),
                new KeyValuePair<int, Type>((int)PageRender.Redirect, typeof(RedirectRender)),
                new KeyValuePair<int, Type>((int)PageRender.FileResponse, typeof(FileResponse)),
                new KeyValuePair<int, Type>((int)PageRender.TemplateSql, typeof(TemplateSqlRender))
            };
        }

        public static List<KeyValuePair<int, Type>> ResponseRenders
        {
            get
            {
                lock (typeof( ResponseRender ))
                    return (_responseRender ?? (_responseRender = Defaults()));
            }
        }
        
        public static ResponseRender Create(PageResponse pageResp)
        {
            var renderKey = ResponseRenders.FirstOrDefault( t => t.Key == (int)pageResp.Render );
            if (renderKey.Value == null)
                throw new NotSupportedException( "No handler for response type: " + pageResp.Render );

            return (ResponseRender)Activator.CreateInstance( renderKey.Value, pageResp.RenderOptions );
        }

        public abstract void Render(HttpContext context);
    }
}
